from trac.core import Component, implements
from trac.perm import PermissionSystem
from trac.db.api import with_transaction

from tracdiscussion.api import IForumChangeListener

class AutoSubscribeModule(Component):
    implements(IForumChangeListener)
    """ This module makes forum administrators to automatically become
        subscribers in forum
    """

    def forum_created(self, context, forum):
        perm_system = PermissionSystem(self.env)
        admins = perm_system.get_users_with_permission('TRAC_ADMIN')

        @with_transaction(self.env)
        def implementation(db):
            values = None
            cursor = db.cursor()

            subscribers = forum['subscribers']
            for admin in admins:
                if admin not in forum['subscribers']:
                    subscribers.append(admin)

            query = '''
                UPDATE forum SET subscribers = %s
                WHERE name = %s AND time = %s
            '''

            values = (' '.join(subscribers), forum['name'], forum['time'])
            self.log.debug(query % values)

            # Trust cursor's escaping
            cursor.execute(query, values)

    # No need to implement these
    def forum_changed(self, context, forum, old_forum):
        pass

    def forum_deleted(self, context, forum):
        pass
